import { createSlice } from "@reduxjs/toolkit";

export const tabListSlice = createSlice({
  name: "tabList",
  initialState: {
    currentTab: '/',
    tabList: [
      { title: '首页', path: '/', readonly: true },
    ]
  },
  reducers:{
    setCurrentTab: (state, action) => {
      state.currentTab = action.payload
    },
    setTabList: (state, action) => {
      state.tabList = action.payload
    },
    // 添加tab
    addTab: (state, action) => {
      const isExist = state.tabList.find(item => item.path === action.payload.path)
      if (!isExist) {
        state.tabList.push(action.payload)
      }
      state.currentTab = action.payload.path
    },
    // 移除tab
    removeTab: (state, action) => {
      const newTabList = state.tabList.filter(item => item.path !== action.payload)
      state.tabList = newTabList
      if (state.currentTab === action.payload) {
        const lastTab = newTabList[newTabList.length - 1]
        state.currentTab = lastTab.path
      }
    },
    // 关闭当前tab - 返回最
    closeCurrentTab: (state) => {
      const currentTabIndex = state.tabList.findIndex(item => item.path === state.currentTab)
      if (currentTabIndex !== -1) {
        state.tabList.splice(currentTabIndex, 1)
        const lastTab = state.tabList[state.tabList.length - 1]
        state.currentTab = lastTab.path
      }
    }
  }
})

export const { setCurrentTab, setTabList, addTab, removeTab, closeCurrentTab } = tabListSlice.actions

export default tabListSlice.reducer